package com.huang.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxyPattern {

    static class ProxyInvocationHandler implements InvocationHandler{

        Object subject;

        public void setSubject(Object subject) {
            this.subject = subject;
        }

        public Object getProxy(){
            return Proxy.newProxyInstance(Subject.class.getClassLoader(),
                    subject.getClass().getInterfaces(),this);
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object result = method.invoke(subject, args);
            doOtherThing();
            return result;
        }

        public void doOtherThing(){
            System.out.println("xixi");
        }
    }

    public static void main(String[] args) {
        //真实对象，传入到动态代理工具中
        RealSubject subject = new RealSubject();
        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
        proxyInvocationHandler.setSubject(subject); //设置到要代理的对象

        //生成动态代理类
        Subject proxy = (Subject)proxyInvocationHandler.getProxy();
        proxy.doWork();
    }
}
